from assets.models import *

from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseNotFound
from django.utils import simplejson

from assets.tags import permission_required2

def collections(request):  
  data = []
  for m in Collection.objects.all().order_by():
    data.append({'id': m.id, 'name': m.name, 'amount': m.assets.count()})
    
  json = simplejson.dumps(data)
  
  return HttpResponse(json, mimetype='text/plain')
  
def asset_collections(request, as_id):  
  asset = get_object_or_404(Asset, id=as_id)
  
  data = []
  for m in asset.collection_set.all().order_by():
    data.append({'id': m.id, 'name': m.name})
  
  json = simplejson.dumps(data)
  
  return HttpResponse(json, mimetype='text/plain')
  
  
@permission_required2('assets.can_change_collection')
def add_collection(request, as_id):  
  asset = get_object_or_404(Asset, id=as_id)
  
  if request.method == 'POST':
    t = int(request.POST['collection'])
    collection = get_object_or_404(Collection, id=t)
    collection.assets.add(asset)
    collection.save()
    return HttpResponse(status=201)
  else:
    response = HttpResponse(status=400)
    return response

@permission_required2('assets.can_change_collection')
def remove_collection(request, as_id):  
  asset = get_object_or_404(Asset, id=as_id)
  
  if request.method == 'POST':
    t = int(request.POST['collection'])
    collection = get_object_or_404(Collection, id=t)
    collection.assets.remove(asset)
    collection.save()
    return HttpResponse(status=204)
  else:
    response = HttpResponse(status=400)
    return response
